<?php

class Iglesias extends Onecore_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model("iglesias_model");
        $this->_moduleName = utf8_encode("Administración de Iglesias");
        $this->_moduleDescription = utf8_encode("Description") . $this->_moduleName;
        $this->_modelInstance = $this->iglesias_model;
    }

    public function add() {
        $success = false;
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " ingresado en forma exitosa";
        $errorList = array();
        $edit = false;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $this->db->trans_begin();
            $data = array(
                "id" => "",
                "data" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
            );
            //$data['data']['SectorId'];
            //$data['data']['name'];
            //
            $log = date('Y-m-d H:i:s');
            $fi = date('Y-m-d');



            //print_r($data);exit;

            if ($this->_modelInstance->save($data, false)) {
                $success = true;
            } else {
                $mensaje = "El " . $itemName . " no pudo ser guardado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
            if ($success) {
                $this->load->model("tipogrupos_model");
                $group_type = $this->tipogrupos_model->get_id_type_congregation();
                $group_data = array(
                    'GrupoId' => '',
                    'nombre' => 'Grupo ' . $data['data']['nombre'],
                    'created' => $log,
                    'Log' => $log,
                    'direccion' => $data['data']['direccion'],
                    'dia_reunion' => 'LUNES',
                    'hora_reunion' => '7:00',
                    'fecha_inicio' => $log,
                    'fecha_termino' => '',
                    'activo' => 'ACTIVO',
                    'observacion' => '',
                    'TipoGrupoId' => $group_type,
                    'SectorId' => $data['data']['SectorId'],
                    'IglesiaId' => $this->db->insert_id()
                );

                $datas = array(
                    "id" => "",
                    "data" => $group_data
                );
                $this->db->trans_commit();
                //$this->db->trans_rollback();
                //print_r($datas);exit;
                //$this->db->insert_string('tbl_grupos', $datas['data']);
                $this->load->model('grupos_model');
                $this->grupos_model->save($datas, false);
            } else {
                $this->db->trans_rollback();
            }
        }
        $res = array(
            "success" => $success,
            "msg" => $mensaje,
            "errors" => $errorList
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function edit() {
        $success = false;
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " editado en forma exitosa";
        $errorList = array();
        $edit = false;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $this->db->trans_begin();
            $data = array(
                "id" => $this->getFilterFieldsToEdit($this->input->post(), $this->_modelInstance->getFields()),
                "data" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
            );
            if ($this->_modelInstance->save($data, true)) {
                $success = true;
            } else {
                $mensaje = "El " . $itemName . " no pudo ser guardado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
            if ($success) {
                $this->db->trans_commit();
            } else {
                $this->db->trans_rollback();
            }
        }
        $res = array(
            "success" => $success,
            "msg" => $mensaje,
            "errors" => $errorList
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function del() {
        $itemName = $this->_modelInstance->getItemName();
        $success = false;
        $mensaje = "El " . $itemName . " seleccionado no pudo ser eliminado";
        $errorList = array();
        $data = array(
            "id" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
        );
        $this->db->trans_begin();
        if ($this->_modelInstance->del($data)) {
            $success = true;
        } else {
            $errorList = array("Error" => $this->_modelInstance->getError());
        }
        if ($success) {
            $mensaje = $itemName . " eliminado en forma exitosa";
            $this->db->trans_commit();
        } else {
            $this->db->trans_rollback();
        }
        $res = array(
            "success" => $success,
            "msg" => $mensaje,
            "errors" => $errorList
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function index() {
        $banner["module_name"] = $this->_moduleName;
        $banner["module_description"] = $this->_moduleDescription;
        $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title", $banner, true);
        $data["page_title"] = "Administración de Iglesias";
        $this->layout->view("/iglesias/index", $data);
    }

    public function loadGrid() {
        $conditions = array();
        $page = $this->input->post("page");
        $rp = $this->input->post("rp");

        $sort = $this->input->post("sortname");
        $dir = $this->input->post("sortorder");

        $query = $this->input->post("query");
        $qtype = $this->input->post("qtype");

        if (!empty($query) && $query !== "null") {
            $obj = array($qtype => $query);
            $fields = $this->_modelInstance->getFields();
            $conditionsFields = $this->_modelInstance->getFieldsConditions();
            $conditions = $this->getConditionsByObject($obj, $conditionsFields, $fields);
            if ($qtype == 'sector_name')
                array_push($conditions, array('field' => 'tbl_sectors.nombre', 'value' => $query, 'type' => 'like'));
        }
        $order = null;
        if (!empty($sort) && $sort !== "null") {
            $obj = json_decode($sort);
            $order = array(
                "field" => $sort,
                "direction" => $dir
            );
        }

        $selected = array();
        $items = $this->_modelInstance->loadGrid($page, $rp, $conditions, $order, $selected);
        $data = array(
            "success" => true,
            "total" => $items["results"],
            "rows" => $items["items"],
            "page" => $items["page"]
        );
        $this->layout->printLike(json_encode($data), "json");
    }

    function getItem() {
        $selected = array();
        $conditions = array();
        $item = $this->input->post('item');
        $res = array();
        if (!empty($item) && $item !== '') {
            $obj = json_decode($item);
            $res = $this->_modelInstance->getItem($obj->IglesiaId);
        }
        $data = array(
            'success' => true,
            'data' => $res
        );
        $this->layout->printLike(json_encode($data), 'json');
    }
    public function loadListByComuna() {
        $selected = array();
        $conditions = array();
        $item = $this->input->post('item');
        $res = array();
        if (!empty($item) && $item !== '') {
            $obj = json_decode($item);
            $res = $this->_modelInstance->loadListByComuna($obj->comuna_id);
        }
        $data = array(
            'success'=>true,
            'results'=>count($res),
            'rows'=>$res
        );
        $this->layout->printLike(json_encode($data), 'json');
    }
}

